package com.example.demo.controller;

import com.example.demo.commom.*;
import com.example.demo.entity.Articleinfo;
import com.example.demo.entity.Userinfo;
import com.example.demo.entity.vo.UserinfoVO;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2023-03-31
 * Time:18:37
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ArticleService articleService;
    @RequestMapping("/reg")
    public AjaxResult reg(Userinfo userinfo) {
        if(userinfo == null
        || !StringUtils.hasLength(userinfo.getUsername())
        || !StringUtils.hasLength(userinfo.getPassword())
        || userinfo.getPassword().length() > 10) {
            return AjaxResult.fail("参数错误",-1);
        }
//        System.out.println(AjaxResult.success(userService.reg(userinfo)));
        //判断用户名是否有人是使用过了
        Userinfo user = userService.getUserByName(userinfo.getUsername());
        if(user != null) {
            return AjaxResult.fail("用户名已存在",-1);
        }
        //密码加盐
        userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));
        return AjaxResult.success(userService.reg(userinfo));
    }




    @RequestMapping("/login")
    public AjaxResult login(HttpServletRequest request,String username,String password) throws InterruptedException {
        //1、判空
        if( !StringUtils.hasLength(username) || !StringUtils.hasLength(password)
        ||password.length() > 10) {
            return AjaxResult.fail("参数错误",-1);
        }
        //校验是否可以进行登录操作
        Userinfo user = userService.getUserByName(username);
        if(user == null || user.getId()<1) {
            return AjaxResult.fail("用户名或密码错误",-1);
        }
        if(user.getState()>4 && user.getUnfreezingtime() > System.currentTimeMillis()) {
            Long waitTime = (user.getUnfreezingtime()-System.currentTimeMillis())/1000;
            return AjaxResult.fail("请等待"+waitTime+"s",-1);
        } else if(user.getState() > 4 && user.getUnfreezingtime() <= System.currentTimeMillis()) {
            user.setState(1);
            userService.upState(user);
        }
        //密码加盐处理过
        if(PasswordUtils.check(password,user.getPassword())) {
            user.setState(1);
            userService.upState(user);
//            //将用户信息存储到session中
//            HttpSession session = request.getSession();//默认是true
//            session.setAttribute(AppVariable.USER_SESSION_KEY,user);
//            //返回前端之前，隐藏敏感信息
////            user.setPassword("");
//            return AjaxResult.success(user);
            //TODO 使用token
            String tokenUUid = TokenUtil.uuid();
            user.setPassword(tokenUUid);
            TokenUtil.map.put("Bearer " + tokenUUid,user);
            return AjaxResult.success(user);
        } else {
            //1、先将state修改
            user.setState(user.getState()+1);
            //2、是否修改取消冻结的最新时间
            if(user.getState() > 4) {
                user.setUnfreezingtime(System.currentTimeMillis()+20000);//当前时间往后家100s
            }
            //更新state+unfreezingtime
            userService.upState(user);
            return AjaxResult.fail("用户名或密码输入错误",-1);
        }
    }

    @RequestMapping("showinfo")
    public AjaxResult showInfo(HttpServletRequest request) {
        UserinfoVO userinfoVO = new UserinfoVO();

        //1、得到当前用户（从session中获取)
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null) {
            return AjaxResult.fail("未登录",-1);
        }
        //Spring提供的深克隆
        BeanUtils.copyProperties(userinfo,userinfoVO);
        //userinfoVO.setUsername(userinfo.getUsername());
        //2、得到用户的文章总数
        if(userinfoVO.getNickname() != null ) {
            userinfoVO.setUsername(userinfoVO.getNickname());
        }
        userinfoVO.setArtCount(articleService.getArtCountByUid(userinfo.getId()));
        return AjaxResult.success(userinfoVO);
    }
    @RequestMapping("/logout")
    public AjaxResult logout(HttpSession session) {
        session.removeAttribute(AppVariable.USER_SESSION_KEY);
        return AjaxResult.success(1);
    }
    @RequestMapping("/getuserbyid")
    public AjaxResult getUserById(Integer id) {
        //空  判断
        if(id == null || id<=0) {
            return AjaxResult.fail("非法参数",-1);
        }
        //查询用户名
        Userinfo userinfo = userService.getUserById(id);
        if(userinfo == null || userinfo.getId()<=0) {
            return AjaxResult.fail("非法参数",-1);
        }
        //设置敏感参数
        userinfo.setPassword("");
        //最终返回vo对象
        UserinfoVO userinfoVO = new UserinfoVO();
        BeanUtils.copyProperties(userinfo,userinfoVO);
        userinfoVO.setArtCount(articleService.getArtCountByUid(userinfo.getId()));
        return AjaxResult.success(userinfoVO);
    }
    //修改个人信息
    @RequestMapping("/upuserinfo")
    public AjaxResult upUserinfo(Userinfo userinfo,String oldpassword,HttpServletRequest request) {
        System.out.println("-------------------------"+userinfo);
        //1、判空
        if(userinfo == null) {
            return AjaxResult.fail("参数错误",-1);
        }
        //获取当前用户信息
        Userinfo user = UserSessionUtils.getUser(request);

        if(user == null || user.getId() <1 ) {
            return AjaxResult.fail("参数有误",-1);
        }
        //如果需要修改密码，需要判断旧密码是否正确
        if(oldpassword != "" && !PasswordUtils.check(oldpassword,user.getPassword())){
            return AjaxResult.fail("参数有误",-1);
        }

        //开始正式修改
        //id
        userinfo.setId(user.getId());
        //密码加盐
        if(userinfo.getPassword()!="") {
            userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));
        }
        return AjaxResult.success(userService.upuserinfo(userinfo));
    }

    //找回密码
    @RequestMapping("/findpassword")
    public AjaxResult findPassword(Userinfo userinfo) {
        System.out.println("------------------"+userinfo);
        //1、判空
        if(userinfo == null || !StringUtils.hasLength(userinfo.getUsername())
        ||!StringUtils.hasLength(userinfo.getPassword()) || !StringUtils.hasLength(userinfo.getLover())) {
            return AjaxResult.fail("参数有误",-1);
        }
        System.out.println("---------------1---"+userinfo);
        //2、查询是否当前
        Userinfo user = userService.getUserByName(userinfo.getUsername());
        if(user == null) {
            return AjaxResult.fail("参数有误",-1);
        }
        System.out.println("---------------2---"+userinfo);
        //3、私密信息是否匹配
        if(!user.getLover().equals(userinfo.getLover())) {
            return AjaxResult.fail("私密信息有误",-1);
        }
        System.out.println("----------------3--"+userinfo);
        //4、修改密码
        user.setPassword(userinfo.getPassword());
        //5、密码加盐
        user.setPassword(PasswordUtils.encrypt(user.getPassword()));
        return AjaxResult.success(userService.upuserinfo(user));
    }
    @RequestMapping("/showcenter")
    public AjaxResult showCenter(HttpServletRequest request) {
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if(userinfo == null || userinfo.getId() < 1) {
            return AjaxResult.fail("请登录后操作");
        }
        Userinfo user  = userService.getUserById(userinfo.getId());
        user.setPassword("");
        return AjaxResult.success(user);
    }
}


































